package com.ljx.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ljx.Domain.MyThreadLocal;
import com.ljx.Domain.R;
import com.ljx.Domain.ShoppingCart;
import com.ljx.Service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("shoppingCart")
public class ShoppingChartController {
    @Autowired
    ShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
        log.info("添加购物车：{}", shoppingCart);
        //查询该用户是否第一次添加套餐或者菜品
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        //保存用户条件
        shoppingCart.setUserId(MyThreadLocal.getThreadLocal());
        wrapper.eq(null != MyThreadLocal.getThreadLocal(), ShoppingCart::getUserId, MyThreadLocal.getThreadLocal());
        //判断添加的是菜品还是套餐
        if (shoppingCart.getDishId() != null) {
            //是菜品
            wrapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        } else {
            //是套餐
            wrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart shoppingCart1 = shoppingCartService.getOne(wrapper);
        if (shoppingCart1 != null) {
            //不是，只需要修改数量number，到数据库
            Integer number = shoppingCart1.getNumber() + 1;
            shoppingCart1.setNumber(number);
            shoppingCartService.updateById(shoppingCart1);
        } else {
            //是第一次，则用save方法
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            shoppingCart1 = shoppingCart;
        }

        return R.success(shoppingCart1);
    }

    /**
     * 展示购物车
     *
     * @return
     */
    @GetMapping("list")
    public R<List<ShoppingCart>> listInShopping() {
        //根据userId查询购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null!=MyThreadLocal.getThreadLocal(),ShoppingCart::getUserId,MyThreadLocal.getThreadLocal());
        //按照更新时间正序排序
        wrapper.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);
        return R.success(shoppingCarts);
    }

    /**
     * 删除购物车
     * @return
     */
    @DeleteMapping("clean")
    public R<String> cleanShopping(){
        //根据userId删除购物车
        Long userId = MyThreadLocal.getThreadLocal();
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null!=userId,ShoppingCart::getUserId,userId);
        shoppingCartService.remove(wrapper);
        return R.success("删除成功");
    }
}
